/*
 * @Author: Mr.Cong Wei
 * @Date: 2022-07-26 20:53:31
 * @LastEditTime: 2022-07-26 20:53:43
 */
async function downloadBook(title, book, p = 5) {
    let c = 0  // 下载完成的片段数量
    const d = {
        book: [],
        ws: []
    }

    if (!isExist(outDir)) {
        fs.mkdirSync(outDir)
    } else {
        fs.readdirSync(outDir).forEach(file => {
            if (!fs.statSync(pathFor(file)).isDirectory()) {
                fs.unlinkSync(pathFor(file))
            }
        })
    }

    for (let i = 0; i < p; i++) {
        const step = Math.ceil(book.length / p)
        d.book.push(i === p - 1 ? book.slice(i * step) : book.slice(i * step, (i + 1) * step))
        d.ws.push(fs.createWriteStream(pathFor(`${title + i}.txt`), {
            flags: 'a'
        }))
        d.ws[i].on('finish', async () => {
            c++
            if (c === p) {
                console.log('\n下载完成，文件归档中...')
                for (let i = 0; i < p; i++) {
                    const target = fs.createWriteStream(pathFor(`/${title}.txt`), {
                        flags: 'a'
                    })
                    const rs = fs.createReadStream(pathFor(`${title + i}.txt`))
                    await pipeSync(rs, target)
                }
                console.log('下载完成！')
                process.exit()
            }
        })
    }

    console.log(`开始下载${title}了：`)

    const bar = new cliProgress.SingleBar({
        format: '下载进度：[{bar}] {percentage}% | 预估时间: {eta}s | {value}/{total}',
        barIncompleteChar: '-'
    }, cliProgress.Presets.rect)
    bar.start(book.length, 0)

    for (let i = 0; i < p; i++) {
        setTimeout(async () => {
            for (const b of d.book[i]) {
                const { $c } = await getHTMLContent(baseURL + b.url, {
                    $c: '#content'
                }, b.title)
                const content = $c.text()
                d.ws[i].write(b.title + '\n')
                d.ws[i].write(content + '\n')
                bar.increment()
            }
            d.ws[i].end()
        })
    }
}
